#
import logging
import os
import time

import openpyxl
import threading
from PyQt5.QtCore import QThread, pyqtSignal



# 全局变量用于存储模板工作簿前三行数据
template_header_rows = []
# Excel中的第一行：列名
def read_txt_file(file_path):
    try:
        with open(file_path, 'r', errors='ignore') as f:
            return f.readlines()
    except FileNotFoundError:

        return None


class OP20ConvertWorker(QThread):
    statusMessage = pyqtSignal(str)

    def __init__(self, files_path):
        super().__init__()
        self.file_names = []
        self.files_path = files_path
        self.new_excel_path = os.path.join(self.files_path, f'NewOP21{time.strftime("%Y%m%d%H%M%S")}.xlsx')
        self.wb = openpyxl.Workbook()
        self.ws = self.wb.active
        self.ws.title = "Data"
        # self.template_path = template_path

    def title_(self) :
        column_names = ['Date', 'Time', 'SNo', 'TP4 (initial signal)_IS [%]', 'TP5 (signal trim)_IS [%]',
                        'TP6 (Move UMS)_Umot[V]', 'TP7 (Check UMS)_IS[%]', 'TP8 (FallBack UMS)_RTime[ms]',
                        'TP13 (Check Pos2)_IS[%]',
                        'TP14 (FallBack Pos2)_RTime[ms]', 'TP15 (final Pos)_IS[%]']
        for col_idx, col_name in enumerate(column_names, start=1):
            self.ws.cell(row=1, column=col_idx, value=col_name)  # 写入标题到第一行，内存中 此时还没有写如excel
    def read_Op20_data(self, file_path):
        all_data = []
        lines = read_txt_file(file_path)
        self.statusMessage.emit(f"Reading file: {file_path}")
        if lines is not None:
            try:
                for i in range(3, len(lines)):
                    if lines[i]:
                        data_row = []
                        if 'NOK' in lines[i].split():
                            time = lines[i].split()[1] + '' + lines[i].split()[2]
                            date = lines[i].split()[0]
                            data_row = [date, time]
                            for y in range(3, len(lines[i].split())-10 ):
                                data_row.append(lines[i].split()[y])
                            all_data.append(data_row)
                            continue
                        else:
                            part_number = lines[i].split()[3]
                            date = lines[i].split()[0]
                            time = lines[i].split()[1] + '' + lines[i].split()[2]
                            Tp4_IS = lines[i].split()[8]
                            Tp5_IS = lines[i].split()[14]
                            Tp6_Umot = lines[i].split()[22]
                            Tp7_IS = lines[i].split()[24]
                            Tp8_RTime = lines[i].split()[30]
                            Tp13_IS = lines[i].split()[33]

                            Tp14_RTime = lines[i].split()[38]
                            Tp15_IS = lines[i].split()[40]

                            data_row = [date, time, part_number,Tp4_IS, Tp5_IS, Tp6_Umot, Tp7_IS, Tp8_RTime, Tp13_IS, Tp14_RTime, Tp15_IS ]
                        all_data.append(data_row)
                    else:
                        pass
            except Exception as e:
                self.statusMessage.emit(f"An error occurred while processing file: {file_path}. Error: {e}")

        return all_data

    def process_file(self, file_name):
        file_path = os.path.join(self.files_path, file_name)
        data = self.read_Op20_data(file_path)
        try:
            # 增加日志记录，打印文件加载前的信息
            for row_data in data:
                self.ws.append(row_data)
            # 增加日志记录，打印文件保存前的信息
                self.wb.save(self.new_excel_path)
        except Exception as e:
            # 更详细的错误日志记录
            raise  # 重新抛出异常，以便在更高层次进行处理（如果需要）
    def get_file_names(self, directory):
        file_list = [f for f in os.listdir(directory) if f.endswith('.txt')]
        return file_list

    def run(self):
        try:
            self.title_()
            self.file_names = self.get_file_names(self.files_path)
            threads = []
            for file_name in self.file_names:
                print(f'Processing file: {file_name}')
                self.statusMessage.emit(f"Processing file: {file_name}")
                file_path = os.path.join(self.files_path, file_name)
                data = self.read_Op20_data(file_path)
                for row_data in data:
                    self.ws.append(row_data)

            self.wb.save(self.new_excel_path)

            self.statusMessage.emit('Conversion completed!')
            self.statusMessage.emit(f'Would save here: {self.new_excel_path}')


        except Exception as e:

            self.statusMessage.emit(f"An error occurred: {e}")
            return False

def read_file(file_path):

    with open(file_path, 'r',errors='ignore') as file:
        lines = file.readlines()
        for i in range(len(lines[3].split())):
            print(f'第{i}个数据：{lines[3].split()[i]}')  # 读取第4行并按空格分割



if __name__ == '__main__':
    path = r'D:\M4REK\test\fall back time'
    txt = r'D:\M4REK\test\fall back time\FBT_240302-1200.txt'
    # new_excel_path = r'D:\M4REK\test\fall back time\OP21 fall back time template.xlsx'
    # try:
    #
    #         worker = OP20ConvertWorker(path)
    #         result = worker.run()
    #         if result:
    #             print("Conversion successful.")
    #         else:
    #             print("Conversion failed.")
    #
    # except Exception as e:
    #     # 捕获可能在初始化过程中出现的任何未处理的异常
    #     logging.error(f"An unexpected error occurred during the execution: {e}")
    result = read_file(txt)
